<?php 
namespace app\policy\tools;
class WxMsg{
    private $appid='wxd0bf7e3be4dc16ef';
    private $secret="26b6cb913c3a14eb5d5ca7ff69523d97";
    public function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token ='dpLK5TnVCZeTiNl7IS25FePelz6jStc6';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        return $tmpStr == $signature ?true:false;
    }
 
    public function send_kefu($data){  //发送客服消息
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->getAccess_token();
        return $this->https_request($url,json_encode($data,JSON_UNESCAPED_UNICODE));
    }
    
    public function upload_cover(){
        $url="https://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->getAccess_token()."&type=image";
        $data=[
            "type"=>'image',
            "access_token"=>$this->getAccess_token(),
            "media"=>new \CURLFile(__DIR__.'/1.jpg')
        ];
        return $this->https_request($url,$data);
    }

    public function getAccess_token() { 
        $data = json_decode(file_get_contents(__DIR__."/access_token.json")); 
        if(empty($data)){
            $data=new \stdClass();
            $data->expire_time=0;
        }
        if ($data->expire_time < time()) { 
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret; 
            $res =$this->https_request($url);
            $res=json_decode($res,true); 
            $access_token = $res['access_token']; 
            if ($access_token) { 
                $data->expire_time = time() + 7000; 
                $data->access_token = $access_token; 
                file_put_contents(__DIR__.'/access_token.json', json_encode($data));
            } 
        } else 
            $access_token = $data->access_token; 
        
        return $access_token; 
    } 


    //https请求（支持GET和POST）  
    private function https_request($url, $data = null) { 
        $curl = curl_init();  
        curl_setopt($curl, CURLOPT_URL, $url);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);  
        

        if (!empty($data)){  
            curl_setopt($curl, CURLOPT_POST, 1);  
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
        }  
        
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
        $output = curl_exec($curl);  
        curl_close($curl);  
        return $output;  
    }  
 
}